//
//  BHMeSettingViewController.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/9/3.
//

import UIKit

class BHMeSettingViewController: BHBaseViewController {
    private let secNamesArray: [String] = ["账号","通用","关于动起来"]
    private let rowNamesArray: [[String]] = [["个人资料"],
                                             ["当前版本","清除缓存"],
                                             ["服务规则","隐私条款"]]
    
    lazy var tableView: UITableView = {
        let view = UITableView.buildTableView(style: .grouped)
        
        view.frame = CGRect(x: 0, y: UIScreen.begainY, width: UIScreen.width, height: UIScreen.showHeight)
        view.register(UINib.init(nibName: "BHMeSettingInfoTableViewCell", bundle: nil), forCellReuseIdentifier: "BHMeSettingInfoTableViewCell")
        view.delegate = self
        view.dataSource = self
        return view
    }()
    fileprivate var cacheSizeStr: String = "0.0M"

    override func viewDidLoad() {
        super.viewDidLoad()

        self.bh_navigationBar.title_label.text = "设置"
        
        self.cacheSizeStr = self.getCacheSize()+"M"

        self.view.addSubview(self.tableView)
       
    }


}
extension BHMeSettingViewController: UITableViewDelegate,UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.secNamesArray.count
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let array = self.rowNamesArray[section]
        return array.count
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 45
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView.init(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 45))
        let a_label = view.viewWithTag(100) as? UILabel
        if a_label != nil {
            a_label!.text = self.secNamesArray[section]
        }else {
            let label = UILabel.init(frame: CGRect(x: 20, y: 20, width: UIScreen.width-40, height: 25))
            label.textColor = .color_222222
            label.font = .systemFont(ofSize: 17, weight: .bold)
            label.tag = 100
            label.text = self.secNamesArray[section]
            view.addSubview(label)
        }
        
        return view
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


        let cell = tableView.dequeueReusableCell(withIdentifier: "BHMeSettingInfoTableViewCell", for: indexPath) as! BHMeSettingInfoTableViewCell
        cell.name_label.text = self.rowNamesArray[indexPath.section][indexPath.row]
        if indexPath.section == 1 { // 通用
            cell.des_label.text = indexPath.row == 0 ? BHCommonTool.appVersion:self.cacheSizeStr
        }else {

            cell.des_label.text = ""
        }
        return cell
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 0 {
            let infoVC = BHPersonalUserInfoViewController.init()
            self.navigationController?.pushViewController(infoVC, animated: true)
        }
        
        if indexPath.section == 1 {
            if indexPath.row == 1 {
                self.clearCache()
            }
        }
        
        if indexPath.section == 2 {
           
            if indexPath.row == 0 { // 服务规则
                BHRouter.shared.bh_goWeb(title: "用户协议", linkUrl: String.userAgreementUrl)
             
            }
            if indexPath.row == 1 { // 隐私协议
                BHRouter.shared.bh_goWeb(title: "隐私政策", linkUrl: String.privateAgreementUrl)
            }
        }
    }
}

// 获取缓存大小 && 清除缓存
extension BHMeSettingViewController {
    func getCacheSize()-> String {
        // 取出cache文件夹目录
        let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first
        // 取出文件夹下所有文件数组
        let fileArr = FileManager.default.subpaths(atPath: cachePath!)
        //快速枚举出所有文件名 计算文件大小
        var size = 0
        for file in fileArr! {
               // 把文件名拼接到路径中
            let path = cachePath! + ("/\(file)")
            // 取出文件属性
            let floder = try! FileManager.default.attributesOfItem(atPath: path)
            // 用元组取出文件大小属性
            for (key, fileSize) in floder {
                // 累加文件大小
                if key == FileAttributeKey.size {
                    size += (fileSize as AnyObject).integerValue
                }
            }
        }
        let totalCache = Double(size) / 1024.00 / 1024.00
        return String(format: "%.2f", totalCache)
    }
    
    
    func clearCache() {
        SVProgressHUD.show()
            // 取出cache文件夹目录
        let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first
        let fileArr = FileManager.default.subpaths(atPath: cachePath!)
        // 遍历删除
        for file in fileArr! {
            let path = (cachePath! as NSString).appending("/\(file)")
            if FileManager.default.fileExists(atPath: path) {
                do {
                    try FileManager.default.removeItem(atPath: path)
                } catch {
                    
                }
            }
        }
        SVProgressHUD.dismiss()
        self.cacheSizeStr = self.getCacheSize()+"M"
        self.tableView.reloadData()
        BHToast.toast(text: "清理缓存成功")
    }
}


